<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户模型类
 */
class User_model extends MY_Model
{
	const TBL_USER = 'user'; //用户表
	const TBL_USER_DATA = 'user_data'; //用户信息表
	const TBL_USER_LOG = 'user_log_login'; //用户登陆记录表
	const PRIMARY_KEY = 'uid';

	protected $_table = 'user';
	protected $primary_key = 'uid';
	protected $protected_attributes = array('uid');

	//protected $belongs_to = array('data' => array('model' => 'user_data_model', 'primary_key' => 'uid'));

	protected $return_type = 'array';

	/**
	 * 根据用户id获取用户基本信息
	 */
	public function get($uid)
	{
		$uid = intval($uid);
		$row = $this->db->get_where('user', array('uid' => $uid))->row_array();
		return $row;
	}

	/**
	 * 根据条件字段获取用户基本信息
	 */
	public function get_by($key, $value = NULL)
	{
        if ( ! is_array($key))
		{
			$key = array($key => $value);
		}
        $row = $this->db->get_where('user', $key)->row_array();
		return $row;
	}

	public function get_data_and_user($uid)
	{
		$uid = $this->db->escape($uid);
		$t_user = $this->db->protect_identifiers(self::TBL_USER, TRUE);
		$t_user_data = $this->db->protect_identifiers(self::TBL_USER_DATA, TRUE);
		$sql = "SELECT u.*, d.* FROM {$t_user} AS u LEFT JOIN {$t_user_data} AS d ON u.uid = d.uid WHERE u.uid = {$uid}";
		$row = $this->db->query($sql)->row_array();

		return $row;
	}

	public function update($data)
	{
		if ($data['uid'])
		{
			$this->db->where('uid', $data['uid']);
			$this->db->limit(1);
			$this->db->update('user', $data);
		}
	}

	public function update_data($data)
	{
		if ($data['uid'])
		{
			$this->db->where('uid', $data['uid']);
			$this->db->limit(1);
			$this->db->update('user_data', $data);
		}
	}

	public function get_user_and_data($uid)
	{
		$uid = $this->db->escape($uid);
		$t_user = $this->db->protect_identifiers(self::TBL_USER, TRUE);
		$t_user_data = $this->db->protect_identifiers(self::TBL_USER_DATA, TRUE);
		$sql = "SELECT u.*, d.* FROM {$t_user} AS u LEFT JOIN {$t_user_data} AS d ON u.uid = d.uid WHERE u.uid = {$uid}";
		$userdata = $this->db->query($sql)->row_array();

		//日、周、月发布数重置
		$today_time = strtotime(date('Y-m-d')); //今日0点时间戳
		$week_time = strtotime('+1 week');
		$month_time = strtotime(date('Y-m') . '-1'); //strtotime('2012-11-1'); //本月1日0点时间戳

		$today_time > $userdata['lastsaletime'] && $userdata['todaysalenum'] = 0;
		$today_time > $userdata['lasthiretime'] && $userdata['todayhirenum'] = 0;
		$week_time > $userdata['lastsaletime'] && $userdata['weeksalenum'] = 0;
		$week_time > $userdata['lasthiretime'] && $userdata['weekhirenum'] = 0;
		$month_time > $userdata['lastsaletime'] && $serdata['monthsalenum'] = 0;
		$month_time > $userdata['lasthiretime'] && $serdata['monthhirenum'] = 0;

		return $userdata;
	}

	/**
	 * 创建用户
	 *
	 * @param $post array $_POST
	 */
	public function create_user($post)
	{
		$insert_id = $this->_insert_user($post);
		$this->_insert_user_data($insert_id);
	}

	/**
	 * 更新最后一次登录的数据（Auth类中登录后调用）
	 *
	 * @param $uid int
	 * @update 2012-10-24 10:45
	 */
	public function update_last_login($user)
	{
		$this->_update_last_login($user);
		$this->_insert_last_login_log($user['uid']);
	}

	/**
	 * 插入用户数据(创建用户时被调用)
	 *
	 * TBL:TBL_USER
	 */
	protected function _insert_user($post)
	{
		$insert_data['ifbroker'] = intval($post['ifbroker']); //用户组id
		$insert_data['username'] = $post['username'];
		$insert_data['password'] = md5($post['password']); //用户密码
		$insert_data['email'] = $post['email']; //用户密码
		$insert_data['group_id'] = $insert_data['ifbroker'] ? 1 : 6; //用户组
		$insert_data['mobile'] = $post['mobile']; //手机号
		$insert_data['created'] = time(); //注册时间
		$insert_data['created_ip'] = sprintf('%u', ip2long($this->input->ip_address())); //注册IP

		$this->db->insert(self::TBL_USER, $insert_data);

		return $this->db->insert_id();
	}

	/**
	 * 用户数据表插入记录(插入用户数据后被调用)
	 *
	 * TBL:TBL_USER_DATA
	 */
	protected function _insert_user_data($insert_id)
	{
		$this->db->insert(self::TBL_USER_DATA, array('uid' => $insert_id));
	}

	/**
	 * 更新登录时间(登录后被调用)
	 *
	 * @param $uid int
	 * @update 2012-10-24 10:45
	 */
	protected function _update_last_login($user)
	{
		$set_data = array(
			'pre_login_time' => 'last_login_time', //上次登录时间
			'pre_login_ip' => 'last_login_ip', //上次登录IP
			'login_times' => 'login_times+1', //登录次数
			);
		$update_data = array(
			'last_login_time' => $this->timestamp, //最后登录时间
			'last_login_ip' => sprintf('%u', ip2long($this->input->ip_address())), //最后登录ip
			);

		$this->db->set($set_data, NULL, FALSE); //第三个参数FALSE，防止被转义
		$this->db->update(self::TBL_USER_DATA, $update_data, array('uid' => $user['uid']));
	}

	/**
	 * 插入登录日志(登录后被调用)
	 *
	 * @param $uid int
	 * @update 2012-10-24 10:45
	 */
	protected function _insert_last_login_log($uid)
	{
		$insert_data = array(
			'uid' => $uid,
			'login_time' => $this->timestamp,
			'login_ip' => sprintf('%u', ip2long($this->input->ip_address())),
			);

		//插入用户登录日志
		$this->db->insert(self::TBL_USER_LOG, $insert_data);
	}

	/**
	 * 获取所有用户信息（分页显示）
	 *
	 * @param $where array
	 * @param $limit int
	 * @param $offset int
	 * @param $orderby string ('uid DESC, created ASC')
	 * @return array
	 */
	public function get_all_list($where = FALSE, $limit = FALSE, $offset = FALSE, $orderby = FALSE)
	{
		$this->_where_list($where);
		$this->db->order_by($orderby);
		$this->db->limit($limit, $offset);
		$result = $this->db->get('user')->result_array();
		return $result;
	}

	public function count_all_list($where)
	{
		$this->_where_list($where);
		return $this->db->count_all_results('user');
	}

	private function _where_list($where)
	{
		//var_dump($where['groupid']);
		if (isset($where['groupid']) && $where['groupid'] != -1 && $where['groupid'] != FALSE)
		{
			$groupid = intval($where['groupid']);
			//普通用户组
			if ($groupid == 0)
			{
				//$this->db->where_in('groupid', array(8, 9));
			}
			else
			{
				$this->db->where('groupid', $groupid);
			}
		}
		if (isset($where['uid']) && $where['uid'] != FALSE)
		{
			$uid = intval($where['uid']);
			$this->db->where('uid', $uid);
		}
		$side = 'after'; //默认 key%
		if (isset($where['like']) && $where['like'] != FALSE) //模糊查询 %key%
		{
			$side = $where['like'];
		}
		if (isset($where['username']) && $where['username'] != FALSE)
		{
			$username = $where['username'];
			$this->db->like('username', $username, $side);
		}
		if (isset($where['email']) && $where['email'] != FALSE)
		{
			$email = $where['email'];
			$this->db->like('email', $email, $side);
		}
	}

	public function lock($uid)
	{
		$this->db->update('user', array('status' => 'lock'), array('uid' => $uid));
	}

	public function unlock($uid)
	{
		$this->db->update('user', array('status' => 'active'), array('uid' => $uid));
	}

	public function active($uid)
	{
		$this->unlock($uid);
	}

	function check_username($str, $uid = FALSE)
	{
		$this->db->from('user');
		$this->db->where('username', $str);
		$uid && $this->db->where('uid !=', $uid);

		return $this->db->count_all_results() === 0;
	}

	function check_email($str, $uid = FALSE)
	{
		$this->db->from('user');
		$this->db->where('email', $str);
		$uid && $this->db->where('uid !=', $uid);

		return $this->db->count_all_results() === 0;
	}
}

/* End of file user_model.php */
/* Location: ./application/models/user_model.php */
